package com.example.redis6.controller;

import com.example.redis6.util.CommonUtil;
import com.example.redis6.util.JsonData;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * description: CaptchaController <br>
 * date: 2021/7/16 13:15 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/api/v1/captcha")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Producer captchaProducer;

    @GetMapping("getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String text = captchaProducer.createText();
        String key = getCaptchaKey(request);

        // 10分钟过期
        redisTemplate.opsForValue().set(key,text,10, TimeUnit.MINUTES
        );
        BufferedImage image = captchaProducer.createImage(text);
        try (
                ServletOutputStream outputStream = response.getOutputStream();
                ){
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("sendCode")
    public JsonData sendCode(@RequestParam(value = "to",required = true) String to,
                             @RequestParam(value = "captcha",required = true) String captcha,
                             HttpServletRequest request){
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        if (cacheCaptcha != null && cacheCaptcha != null && cacheCaptcha.equalsIgnoreCase(captcha)){
            redisTemplate.delete(key);
            // todo 发送验证码
            return JsonData.buildSuccess();
        }else {
            return JsonData.buildError("验证码错误");
        }
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captcha:"+CommonUtil.MD5(ip+userAgent);

        return key;
    }
}
